import os
import sys

from my_tool import Color, Bash, File, Git


def branch_check(path, check_branchs):
    """
    查询/检出指定路径下的所有包到指定分支
    :param path:
    :param check_branchs: 需要检出的分支，支持多分支，如：brancha,branchb
    :return:
    """
    if path is None or check_branchs is None:
        Color.red('路径或分支不存在')
        sys.exit(0)
    files = File.path_files(path)
    checkout = 'N'
    if len(args) > 4:
        checkout = args[4]
    gitpull = False
    if len(args) > 5 and args[5] == 'pull':
        gitpull = True
    for filepath in files:
        if os.path.isfile(filepath):
            continue
        if not Git.is_git(filepath):
            continue
        if checkout == 'Y':
            Bash.only_run_cmd('git -C {} fetch'.format(filepath), False)
        module_name = Bash.get_run_cmd_result('basename ' + filepath).replace('\n', '')
        if checkout == 'Y':
            nothing_commit = Bash.get_run_cmd_result('git -C {} status | grep "nothing to commit"'.format(filepath))
            if not nothing_commit:
                Color.yellow('{} 模块有未提交的代码'.format(module_name))
                continue
        local_branch = Git.get_branch(filepath)
        for check_branch in check_branchs.split(','):
            have_branch = Bash.get_run_cmd_result(
                'git -C {} branch -a | grep -E "^\\s*{}$|/{}$"'.format(filepath, check_branch, check_branch), False,
                True)
            if have_branch:
                if checkout == 'Y':
                    if local_branch == check_branch:
                        break
                    else:
                        Bash.only_run_cmd('git -C {} checkout {}'.format(filepath, check_branch), True)
                        if gitpull:
                            Bash.only_run_cmd('git -C {} pull'.format(filepath), True)
                        break
                else:
                    Color.green(module_name)


if __name__ == '__main__':
    """
    # 检出/检查指定分支
    python3 jar_package.py branch <path> <check_branchs> [checkout] [pull]
    """
    args = sys.argv
    try:
        if args[1] == 'branch':
            branch_check(args[2], args[3])
        else:
            Color.red('参数有误')
    except BaseException as e:
        Color.red(e)
        sys.exit(0)
